import React, { PureComponent, Fragment } from 'react'
import { connect } from 'react-redux';

import { Layout } from 'antd';
import {
    PageHeader,
    Table,
    ButtonEvent,
    Status,
    Modal,
    Form,
    Tip
} from '../../../components';
import { mainService } from '../../../service';
import { cmsCateAction as cateAction, mainAction } from '../../../store/action';

const breadcrumbList = [{
    title: '内容管理'
}, {
    title: '分类管理'
}];
class Index extends PureComponent{
    state = {
        apiname:'cms/category',
        modalTitle:"添加分类",
        visible:false,
        //设置表单按钮
        tableBtn:[
            {key:1,type:'primary',value:'添加',onClick:()=>{ this.openModel('add'); }}
        ],
        inputdata : [],
        footerbar:null,
        //表格colums
        columns:[
            {title: '名称',dataIndex: 'name',width:250, tree:true}
            ,{title: '栏目ID',dataIndex: 'id',width:80}
            ,{title: '英文名',dataIndex: 'dirname',width:150}
            ,{title: '状态',dataIndex: 'status',width:100,render:(value,row)=>{
                return <Status ontext="启用" offtext="禁用" value={value} onClick = { (bool)=>{ this.status(bool,row) } } />
            }}
            ,{ title: '操作', key: 'operation', width: 150, render: (value) =><ButtonEvent data={ [
                {key:1,value:'修改',size:'small',onClick:()=>{
                    this.editModel(value)
                }},
                {key:2,type:'danger',value:'删除',size:'small',onClick:()=>{
                    this.delModel(value)
                }}
            ]}/> }
        ]

    }
    render(){
        const { loading, list, emptyText, catetree } = this.props;
        const { tableBtn, columns, visible, modalTitle, inputdata, footerbar } = this.state;
        let ndata=inputdata;
        if(inputdata.length>0){
            ndata[0].treeData=catetree;
        }
        const locale = {
            emptyText
        }

        const action = <ButtonEvent data={ [
            {key:1,type:'primary',value:'刷新',size:'small',onClick:()=>{
                this.refresh()
            }}
        ]}/>;
        return(
            <Fragment>
                <PageHeader title={breadcrumbList[1]['title']} breadcrumbList={breadcrumbList} action={action}></PageHeader>

                <Layout.Content style={{margin:'24px',padding:'24px 32px 8px',backgroundColor:'#fff'}}>
                    <ButtonEvent
                        data={ tableBtn }
                        style={{marginBottom:16}}
                    />
                    <Table
                        columns = {columns}
                        dataSource = { list }
                        locale = {locale}
                        loading = { loading }
                        indentSize = { 30 }
                        pagination = {false}
                    />
                </Layout.Content>


                <Modal
                    visible={visible}
                    title = {modalTitle}
                    onCancel={this.handleCancel}
                    maskClosable={false}
                    footer={ footerbar }
                    destroyOnClose={true}
                    drag={true}
                    className="modal-top"
                >
                    <Form
                        layout = 'horizontal'
                        data = {ndata}
                        wrappedComponentRef={(form) => this.formRef = form}
                    />
                </Modal>
            </Fragment>
        )
    }

    //重置
    refresh = () => {
        const { bindLoading } = this.props;
        bindLoading(true)
        this.loadList();
    }
    //关闭弹窗
    handleCancel=()=>{
        this.setState({
            visible:false
        })
    }

    /**
     * 按钮工具操作
     */
    //openModel
    openModel=(type)=>{
        switch (type) {
            case 'add':
                this.addFormJsx();
                break;
            default:
                break;
        }
    }
    editModel = (obj)=>{
        this.setState({
            modalTitle:'修改分类'
        });
        this.editFormJsx(obj);
    }
    delModel = (obj)=>{
        let id=[];
        id.push(obj.id)
        this.delete(id);
    }

    /**
     * 数据处理
     * */
    //保存数据
    save = async (type)=>{
        const { apiname } = this.state;
        this.changeBtnLoading(true);
        let values = await this.formRef.getItemsValue();
        if(values){
            try{
                let res = await mainService.crud(apiname+"/"+type,values);
                this.tipMsg(res);
            }catch{
                this.tipMsg({code:3,msg:"网络错误"});
            }
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    delete = (arr)=>{
        const { apiname } = this.state;
        Tip.Modal('您真的要删除?','confirm',{
            onOk:async ()=>{
                let res = await mainService.crud(apiname+"/del",arr);
                this.tipMsg(res);
            }
        })
    }

    //状态修改
    status = async (value,item)=>{
        const { apiname } = this.state;
        let data={
            id:item.id,
            showed:item.showed,
            pid:item.pid,
            title:item.title
        };
        if(value){
            data['status']=1;
        }else{
            data['status']=0;
        }
        let res = await mainService.crud(apiname+'/edit',data);
        this.tipMsg(res);
    }
    //消息提示
    tipMsg = (res,type='')=>{
        const { bindLoading } = this.props;
        if(res.code===0){
            this.handleCancel();
            Tip.Message(res.msg,'success');
            bindLoading(true)
            this.loadList();
        }else{
            Tip.Message(res.msg,'error')
        }
    }
    //保存按钮状态
    changeBtnLoading = (bool)=>{
        this.props.bindBtnLoading(bool)
    }

    //form 表单生成
    addFormJsx=()=>{
        const { fielddata } = this.props;
        this.getCateTree();
        //初始化添加的form表单数据
        let fielddataarr=[];
        for(let i=0;i<fielddata['arr'].length;i++){
            let v = fielddata['arr'][i];
            let o = {};
            o = Object.assign({},fielddata[v]);
            fielddataarr.push(o)
        }

        this.setState({
            inputdata:fielddataarr,
            visible:true,
            footerbar:
            <ButtonEvent data={ [
                {key:1,value:'取消',onClick:this.handleCancel},
                {key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{
                    this.save('add')
                }}
            ]}/>
        });
    }
    //编辑数据
    editFormJsx = (obj)=>{
        const { fielddata } = this.props;
        this.getCateTree(obj['id']);
        //初始化添加的form表单数据
        let fielddataarr=[];
        for(let i=0;i<fielddata['arr'].length;i++){
            let v = fielddata['arr'][i];
            let o = {};
            o = Object.assign({},fielddata[v]);
            o.value = obj[v];
            fielddataarr.push(o)
        }

        let id = {type:'input.hidden',title:'ID',name:'id',value:obj['id'],disabled:true};
        fielddataarr.push(id);
        this.setState({
            inputdata:fielddataarr,
            visible:true,
            footerbar:
            <ButtonEvent data={ [
                {key:1,value:'取消',onClick:this.handleCancel},
                {key:2,type:'primary',value:'保存',btnloading:"1",onClick:()=>{
                    this.save('edit')
                }}
            ]}/>
        });
    }

    //加载ruletree
    getCateTree = async (id=0)=>{
        const { apiname } = this.state;
        let res = await mainService.getTree(apiname+'/catetree',0,id);
        this.props.bindTreeData(res);
    }

    //获取列表
    loadList = async ()=>{
        const { bindList } = this.props;
        const { apiname } = this.state;
        let res = await mainService.getlist(apiname,{});
        bindList(res)
    }

    //主键加载完成
    componentDidMount(){
        this.loadList();
    }
}
const mapStateToProps = (state)=>{
    const name = 'cms_cate';
    const list = state.getIn([name,'list']).toJS();
    const loading = state.getIn([name,'loading']);
    const total = state.getIn([name,'total'])
    const fielddata = state.getIn([name,'fielddata']).toJS();
    const emptyText = state.getIn([name,'emptyText']);
    const catetree = state.getIn([name,'catetree']).toJS();
    return{
        list,
        loading,
        total,
        fielddata,
        emptyText,
        catetree
    }
}
const mapDispatchToProps = (dispatch)=>{
    return{
        bindLoading(loading){
            dispatch(cateAction.setLoading(loading))
        },
        bindList(res){
            if(res.code === 0){
                let list=res.data;
                dispatch(cateAction.getList(list.rows,list.total));
            }else{
                dispatch(cateAction.setEmptyText(res.msg));
            }
            dispatch(cateAction.setLoading(false));
        },
        bindTreeData(res){
            if(res.code === 0){
                let list=res.data;
                dispatch(cateAction.setTreeData(list));
            }else{
                Tip.Message('网络错误,请刷新重试','error')
            }
        },
        bindBtnLoading(bool){
            dispatch(mainAction.setBtnLoading(bool));
        }
    }
}
export default connect(mapStateToProps,mapDispatchToProps)(Index);